package org.bdware.irs.backend.servicesImpl;
import org.bdware.irs.IrsBootWithTcp;
import org.bdware.irs.IrsConfig;
import org.bdware.irs.backend.dto.DoTypeInSuffix;
import org.bdware.irs.backend.services.PreAndSuffixService;
import com.nimbusds.jose.Algorithm;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.Curve;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.gen.ECKeyGenerator;
import org.bdware.irs.server.http.IrsMain;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class IRHelperServiceImpl implements PreAndSuffixService {

    @Override
    public String prefixGenerator() {
        return UUID.randomUUID().toString();
    }

    @Override
    public String prefixGeneratorInIRS() {
        return IrsBootWithTcp.irsConfig.prefix + "." + prefixGenerator();
    }

    @Override
    public String suffixGenerator(String type) {
        return DoTypeInSuffix.generatePrefixOfSuffix(type) + "." + UUID.randomUUID().toString();
    }

    @Override
    public String doiGenerator(String type) {
        return IrsBootWithTcp.irsConfig.prefix + "/" + suffixGenerator(type);
    }

    //这里的key直接用申请用户对应的DOI号
    @Override
    public String keyGenerator(String key) throws JOSEException {
        JWK jwk;
        jwk = new ECKeyGenerator(Curve.P_256)
                .keyUse(KeyUse.SIGNATURE) // indicate the intended use of the key
                .keyID(key) // give the key a unique ID
                .algorithm(new Algorithm("ES256")) //
                .generate();
        //the private and public RSA JWK parameters
        String  skJson = jwk.toJSONString();
        System.out.println("=====jwk=====");
        System.out.println(skJson);
        //the public RSA JWK parameters only
        String pkJson = jwk.toPublicJWK().toJSONString();
        //TODO save the jwk info along with DOI of register user/account
        return skJson;
    }
}
